package com.lost.octopus.es.helper.entity.wrapper;

import com.lost.octopus.es.helper.entity.model.FieldConfig;
import com.lost.octopus.es.helper.annotation.EsSearch;
import com.lost.octopus.es.helper.constant.ParameterConstant;

import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.springframework.stereotype.Component;

/**
 * 多个或者条件.should单个条件查询
 * 如 and ( x=val or x1=val or x2=val)
 * 如查询 名称、身份证号 模糊值=1的数据
 * 需要同步配置 {@link EsSearch#otherParam()}
 * 如：当phoneOrIdCard有值 查询手机（phone）或身份证（idCard）含 123的 配置 phone,idCard
 * <br/>
 * 注解：{@code @EsSearch(queryType = EsQueryMultiplyKeyWrapper.class, fieldMatchType = EsFieldMatchType.wildcard, otherParam = "tel,idCard")}
 * <br/>
 * 示例：{@code "1"}
 * <br/>
 * 效果：{@code {"bool":{"should":[{"wildcard":{"tel":{"wildcard":"*1*"}}},{"wildcard":{"idCard":{"wildcard":"*1*"}}}]}} }
 * @author zhangbh
 **/
@Component
public class EsQueryMultiplyKeyWrapper extends AbstractQueryWrapper {

    @Override
    public QueryBuilder addWrapper(BoolQueryBuilder builder, FieldConfig field) {
        String fieldName = field.getName();
        // 定制化对象，存储查询的其他参数属性名
        String[] attrKeys = field.getOtherParam().split(ParameterConstant.SEPARATOR);
        if (attrKeys.length == 0) {
            throw new IllegalArgumentException(String.format("字段%s使用多属性查询模式，没有设置paramKeys属性", fieldName));
        }
        BoolQueryBuilder orQuery = QueryBuilders.boolQuery();
        // 多个字段模糊查询
        for (String attrKey : attrKeys) {
            FieldConfig queryConfig = field.copy().setName(attrKey);
            orQuery.should(useBuilder(queryConfig));
        }
        builder.must(orQuery);
        return orQuery;
    }
}
